#include "include/widgets/trading_widget.hpp"

TradingWidget::TradingWidget(TradingSystem *tradingSystem, QWidget *parent)
    : QWidget(parent), m_tradingSystem(tradingSystem),
      m_currentStockPrice(0.0) {
  setupUI();
  setupConnections();
  updateBalanceDisplay();
}

void TradingWidget::setupUI() {
  // 创建主布局
  auto *mainLayout = new QVBoxLayout(this);

  // 股票信息
  auto *stockInfoGroup = new QGroupBox("股票信息", this);
  auto *stockInfoLayout = new QVBoxLayout(stockInfoGroup);
  m_stockInfoLabel = new QLabel("未选择股票", this);
  stockInfoLayout->addWidget(m_stockInfoLabel);

  // 账户信息
  auto *accountInfoGroup = new QGroupBox("账户信息", this);
  auto *accountInfoLayout = new QVBoxLayout(accountInfoGroup);
  m_balanceLabel = new QLabel("可用资金: ¥0.00", this);
  accountInfoLayout->addWidget(m_balanceLabel);

  // 交易操作
  auto *tradingGroup = new QGroupBox("交易操作", this);
  auto *tradingLayout = new QVBoxLayout(tradingGroup);

  // 股数选择
  auto *sharesLayout = new QHBoxLayout();
  auto *sharesLabel = new QLabel("股数:", this);
  m_sharesSpinBox = new QSpinBox(this);
  m_sharesSpinBox->setRange(1, 100000);
  m_sharesSpinBox->setSingleStep(1);
  m_sharesSpinBox->setValue(1);
  sharesLayout->addWidget(sharesLabel);
  sharesLayout->addWidget(m_sharesSpinBox);

  // 总成本
  auto *totalCostLayout = new QHBoxLayout();
  auto *totalCostDescLabel = new QLabel("总成本:", this);
  m_totalCostLabel = new QLabel("¥0.00", this);
  totalCostLayout->addWidget(totalCostDescLabel);
  totalCostLayout->addWidget(m_totalCostLabel);

  // 买入卖出按钮
  auto *buttonLayout = new QHBoxLayout();
  m_buyButton = new QPushButton("买入", this);
  m_buyButton->setEnabled(false);
  m_sellButton = new QPushButton("卖出", this);
  m_sellButton->setEnabled(false);

  buttonLayout->addWidget(m_buyButton);
  buttonLayout->addWidget(m_sellButton);

  tradingLayout->addLayout(sharesLayout);
  tradingLayout->addLayout(totalCostLayout);
  tradingLayout->addLayout(buttonLayout);

  // 添加到主布局
  mainLayout->addWidget(stockInfoGroup);
  mainLayout->addWidget(accountInfoGroup);
  mainLayout->addWidget(tradingGroup);
  mainLayout->addStretch();

  // 设置样式
  m_buyButton->setStyleSheet(
      "QPushButton { background-color: #e74c3c; color: white; }");
  m_sellButton->setStyleSheet(
      "QPushButton { background-color: #2ecc71; color: white; }");
}

void TradingWidget::setupConnections() {
  connect(m_sharesSpinBox, QOverload<int>::of(&QSpinBox::valueChanged), this,
          &TradingWidget::updateTotalCost);
  connect(m_buyButton, &QPushButton::clicked, this,
          &TradingWidget::onBuyClicked);
  connect(m_sellButton, &QPushButton::clicked, this,
          &TradingWidget::onSellClicked);

  // 连接账户更新信号
  connect(m_tradingSystem, &TradingSystem::accountUpdated, this,
          &TradingWidget::onAccountUpdated);
}

void TradingWidget::onStockSelected(const QString &stockCode,
                                    const QString &stockName, double price) {
  m_currentStockCode = stockCode;
  m_currentStockName = stockName;
  m_currentStockPrice = price;

  // 更新UI
  m_stockInfoLabel->setText(QString("%1 (%2) 当前价格: ¥%3")
                                .arg(stockName, stockCode)
                                .arg(price, 0, 'f', 2));

  m_buyButton->setEnabled(true);
  m_sellButton->setEnabled(true);

  updateTotalCost();
}

void TradingWidget::updateTotalCost() {
  int shares = m_sharesSpinBox->value();
  double totalCost = shares * m_currentStockPrice;
  m_totalCostLabel->setText(QString("¥%1").arg(totalCost, 0, 'f', 2));

  // 检查余额是否足够，更新买入按钮状态
  UserAccount *account = m_tradingSystem->getCurrentAccount();
  if (account && account->getBalance() < totalCost) {
    m_buyButton->setEnabled(false);
    m_buyButton->setToolTip("余额不足");
  } else if (!m_currentStockCode.isEmpty()) {
    m_buyButton->setEnabled(true);
    m_buyButton->setToolTip("");
  }

  // 检查持仓是否足够，更新卖出按钮状态
  bool canSell = false;
  if (account) {
    Position *pos = account->getPosition(m_currentStockCode);
    canSell = (pos && pos->shares >= shares);
  }
  m_sellButton->setEnabled(canSell);
  if (!canSell) {
    m_sellButton->setToolTip("持仓不足");
  } else {
    m_sellButton->setToolTip("");
  }
}

void TradingWidget::updateBalanceDisplay() {
  UserAccount *account = m_tradingSystem->getCurrentAccount();
  if (account) {
    double balance = account->getBalance();
    m_balanceLabel->setText(QString("可用资金: ¥%1").arg(balance, 0, 'f', 2));
  } else {
    m_balanceLabel->setText("可用资金: ¥0.00");
  }
}

void TradingWidget::onBuyClicked() {
  if (m_currentStockCode.isEmpty() || m_currentStockPrice <= 0) {
    QMessageBox::warning(this, "错误", "请先选择股票");
    return;
  }

  int shares = m_sharesSpinBox->value();
  double totalCost = shares * m_currentStockPrice;

  UserAccount *account = m_tradingSystem->getCurrentAccount();
  if (!account) {
    QMessageBox::warning(this, "错误", "用户未登录");
    return;
  }

  if (account->getBalance() < totalCost) {
    QMessageBox::warning(this, "错误", "余额不足");
    return;
  }

  // 执行买入操作
  if (account->buy(m_currentStockCode, m_currentStockName, shares,
                   m_currentStockPrice)) {
    QMessageBox::information(this, "成功",
                             QString("成功买入 %1 (%2) %3 股，总成本：¥%4")
                                 .arg(m_currentStockName, m_currentStockCode)
                                 .arg(shares)
                                 .arg(totalCost, 0, 'f', 2));
    updateBalanceDisplay();
  } else {
    QMessageBox::critical(this, "失败", "买入操作失败");
  }
}

void TradingWidget::onSellClicked() {
  if (m_currentStockCode.isEmpty() || m_currentStockPrice <= 0) {
    QMessageBox::warning(this, "错误", "请先选择股票");
    return;
  }

  int shares = m_sharesSpinBox->value();

  UserAccount *account = m_tradingSystem->getCurrentAccount();
  if (!account) {
    QMessageBox::warning(this, "错误", "用户未登录");
    return;
  }

  Position *pos = account->getPosition(m_currentStockCode);
  if (!pos || pos->shares < shares) {
    QMessageBox::warning(this, "错误", "持仓不足");
    return;
  }

  // 执行卖出操作
  if (account->sell(m_currentStockCode, m_currentStockName, shares,
                    m_currentStockPrice)) {
    double totalRevenue = shares * m_currentStockPrice;
    QMessageBox::information(this, "成功",
                             QString("成功卖出 %1 (%2) %3 股，总收入：¥%4")
                                 .arg(m_currentStockName, m_currentStockCode)
                                 .arg(shares)
                                 .arg(totalRevenue, 0, 'f', 2));
    updateBalanceDisplay();
    updateTotalCost(); // 更新卖出按钮状态
  } else {
    QMessageBox::critical(this, "失败", "卖出操作失败");
  }
}

void TradingWidget::onAccountUpdated() {
  updateBalanceDisplay();
  updateTotalCost();
}
